package com.swm.jdo;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import org.springframework.stereotype.Repository;

import com.swm.dao.UserDao;
import com.swm.model.User;

@Repository
public class UserDaoImpl implements UserDao {

	PersistenceManagerFactory pmf = PMF.get();
	
	public UserDaoImpl(){
		//this.pmf = PMF.get();
	}
	
	protected PersistenceManager getPersistenceManager(){
		return pmf.getPersistenceManager();
	}
	

	@Override
	public void Delete(String userID){
		PersistenceManager pm = getPersistenceManager();			
		
        try {
        	User user = this.find(userID);
        	
            if(user != null){
            	pm.makePersistent(user);
            }
        } finally {
            pm.close();
        }
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<User> find(){
		PersistenceManager pm = getPersistenceManager();
		List<User> users;
		try{
			Query query = pm.newQuery(User.class);
			users = (List<User>) query.execute();
			users.size();
		} finally{
			pm.close();
		}
		return users;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public User	find(String userID){
		PersistenceManager pm = getPersistenceManager();
		List<User> users;
        try {
        	Query query = pm.newQuery( User.class, "id == idField");
        	query.declareParameters("String idField");
        	
        	users = (List<User>) query.execute(userID);
        	users.size();        	
        } finally{
        	pm.close();
        }
        
        if(users.size() > 0)
        	return users.get(0);
        else
        	return null;
	}		
	
	@Override
	public void Add(User user) {
		// TODO Auto-generated method stub
		PersistenceManager pm = getPersistenceManager();
		if ( pm != null ){
	        try {
	            pm.makePersistent(user);
	        } finally {
	            pm.close();
	        }
		}
	}

	@Override
	public void Update(User user) {
		// TODO Auto-generated method stub
		PersistenceManager pm = getPersistenceManager();
		
        try {
            pm.makePersistent(user);
        } finally {
            pm.close();
        }
	}
}
